// pages/profile/profile.js
const app = getApp()
const api = require('../../utils/api')
const util = require('../../utils/util')
const bluetoothUtils = require('../../utils/bluetoothUtils')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl: '/images/profile/user_pic.png',
    nickName: '舒福德智能睡眠体验官',
    hasUserData: false, //是否获取到酒店信息
    noData_text: '暂未入住',
    hotelMsg: {
      hotelName: '',
      phone: '',
      location: ''
    },
    btnContext: '断开连接',
    data_switch: true, //数据开关默认开启
    hasConnect: false, //是否已经连接智能床
    antiSnore_status: '关闭',
    logoutFlag: false,
    dialogShow1: false,
    subscribeFlag: false,
    msg: {},
    bind_state: '智能床左侧',
    tipsFlag: false, //数据开关tips
  },
  toAbout: function () {
    wx.navigateTo({
      url: '/pages/profile/About/about',
    })
  },
  toLogout: function () {
    this.setData({
      logoutFlag: false,
      dialogShow1: true,
      'msg.content': '退出登录后将自动断开智能床连接，您将无法使用智能床一键入眠等功能，也无法查看睡眠报告，是否确认退出？',
      'msg.btntext': '退出登录',
      'msg.title': '',
      'msg.tips': 1
    })
  },
  toCancellation: function () {
    this.setData({
      logoutFlag: false,
      dialogShow1: true,
      'msg.content': '帐号注销后，账号下的所有数据将被彻底删除，并且无法使用智能床一键入眠等功能，是否确认注销？',
      'msg.btntext': '注销',
      'msg.title': '',
      'msg.tips': 1
    })
  },
  showLogout: function () {
    this.setData({
      logoutFlag: true
    })
  },
  showDisconnect: function () {
    this.setData({
      dialogShow1: true,
      'msg.content': '断开智能床连接后，您将无法使用智能床一键入眠等功能，确认断开连接？',
      'msg.btntext': '断开连接',
      'msg.title': '',
      'msg.tips': 1
    })
  },
  dialogCancel: function () {
    this.setData({
      bluetoothFlag: false,
      bluetoothFlag2: false,
      // userLocationFlag: false
    })
  },
  cancel: function () {
    this.setData({
      logoutFlag: false
    })
  },
  toSnoreDetail: function () {
    const _this = this
    if (this.data.hasConnect != false) {
      wx.navigateTo({
        url: '/pages/profile/antiSnore/antisnore?switch=' + _this.data.antiSnore_status,
      })
    } else {
      util.myShowToast('未连接智能床')
    }

  },
  toSubscribe: async function (e) {
    const _this = this
    let index = e.currentTarget.dataset.index
    console.log('index', index)
    if (index == 0) {
      const _this = this
      wx.requestSubscribeMessage({
        tmplIds: ['9r4DM3t-6PaF6MWRFJBwvst8wjCKhwR7aByDpxGaRGw', 'yT2ktR0dTazLfnAcg9YZ61QDzI8aAr6pTdyfTbmKpww'],
        success(res) {
          let sum = 0
          for (let key in res) {
            if (res[key] == 'reject') {
              sum = sum + 1
            }
          }
          console.log('sum', sum)
          if (sum > 0) {
            _this.setData({
              subscribeFlag: false
            })
          } else {
            _this.setData({
              subscribeFlag: true
            })
          }
          console.log('订阅授权成功', res, getApp().globalData.needsubscribe)
        },
        fail(res) {
          console.log('订阅失败', res)
        }
      })
    } else {
      this.setData({
        subscribeFlag: false
      })
    }
  },
  getUserInfo: function () {
    const _this = this
    let data = {
      user_id: app.globalData.userId
    }
    util.myShowLoading('用户信息加载中')
    api.getBindInfo(data, app.globalData.token).then(res => {
      util.myHideLoading()
      if (res.data.code == 200) {
        console.log('res', res)
        let hoteldata = res.data.data
        if (hoteldata.device_id != undefined) {
          if (hoteldata.bed_side == 1) {
            this.setData({
              bind_state: '智能床左侧'
            })
          } else if (hoteldata.bed_side == 0) {
            this.setData({
              bind_state: '智能床右侧'
            })
          } else {
            this.setData({
              bind_state: '智能床'
            })
          }
          _this.setData({
            data_switch: hoteldata.data_switch,
            antiSnore_status: hoteldata.snore_switch == true ? '开启' : '关闭',
            'hotelMsg.hotelName': hoteldata.hotel.name,
            'hotelMsg.phone': hoteldata.hotel.phone,
            'hotelMsg.location': hoteldata.hotel.address
          })
          if (app.globalData.bluetooth_connected == true || app.globalData.bluetooth_connected2 == true) {
            _this.setData({
              hasConnect: true,
              hasUserData: true,
            })
          } else {
            _this.setData({
              hasConnect: false,
              hasUserData: false,
            })
          }
        }
      } else {
        util.myShowToast('服务器有点小问题')
      }
    })
  },
  connectBed: function () {
    this.permissionCheck()
  },
  dataSwitch: function () {
    const _this = this
    let index = 0
    if (this.data.data_switch == true) {
      util.myShowLoading('正在关闭')
      index = 0
    } else {
      util.myShowLoading('正在打开')
      index = 1
    }
    let data = {
      open_switch: index
    }
    api.setDataSwitch(data, app.globalData.token).then(res => {
      if (res.data.code == 200) {
        util.myHideLoading()
        if (index == 0) {
          this.setData({
            data_switch: false
          })
          app.globalData.dataswitch = false
        } else {
          app.globalData.dataswitch = true
          this.setData({
            data_switch: true
          })
        }
      } else {
        util.myShowToast(res.data.msg)
      }
    })
  },
  changeSwitch: function (e) {
    if (this.data.data_switch == true) {
      this.setData({
        dialogShow1: true,
        'msg.content': '关闭数据开关后将无法生成睡眠报告，确认关闭吗？',
        'msg.btntext': '确定',
        'msg.title': '',
        'msg.tips': 1
      })
    } else {
      util.myShowLoading('正在打开')
      let data = {
        open_switch: 1
      }
      api.setDataSwitch(data, app.globalData.token).then(res => {
        if (res.data.code == 200) {
          util.myHideLoading()
          this.setData({
            data_switch: true
          })
          app.globalData.dataswitch = true
        } else {
          util.myShowToast(res.data.msg)
        }
      })
    }


  },
  dialogHandle1: async function (e) {
    console.log('eeeeee', e)
    this.setData({
      dialogShow1: e.detail.params
    })
    console.log('e', this.data.msg)
    if (e.detail.text == 'confirm') {
      if (this.data.msg.btntext == '退出登录') {
        const _this = this
        app.globalData.failDevice = null
        let data = {
          user_id: app.globalData.userId
        }
        util.myShowLoading()
        api.unBind(data, app.globalData.token).then(async function (res) {
          if (res.data.code == 200) {
            console.log('解绑成功')
            _this.setData({
              hasConnect: false,
              hasUserData: false,
              'hotelMsg.hotelName': "",
              'hotelMsg.phone': "",
              'hotelMsg.location': "",
              antiSnore_status: '关闭'
            })
            util.myHideLoading()
            if (app.globalData.bluetoothInfo != null) {
              await bluetoothUtils.closeBLEConnection(app.globalData.bluetoothInfo.deviceID)
              app.globalData.bluetoothInfo = null
            }
            if (app.globalData.bluetoothInfo2 != null) {
              await bluetoothUtils.closeBLEConnection(app.globalData.bluetoothInfo2.deviceID)
              app.globalData.bluetoothInfo2 = null
            }
            app.globalData.token = null
            app.globalData.deviceId = null
            app.globalData.nopermission = true
            wx.switchTab({
              url: '/pages/index/index?nopermission=true',
            })
          } else {
            console.log('error', res.data.msg)
            util.myShowToast(res.data.msg)
          }
        })
      }
      if (this.data.msg.btntext == '注销') {
        this.cancellation()
      }
      if (this.data.msg.btntext == "断开连接") {
        const _this = this
        app.globalData.deviceId = null
        app.globalData.failDevice = null
        let data = {
          user_id: app.globalData.userId
        }
        util.myShowLoading()
        api.unBind(data, app.globalData.token).then(async function (res) {
          if (res.data.code == 200) {
            console.log('解绑成功')
            _this.setData({
              hasConnect: false,
              hasUserData: false,
              'hotelMsg.hotelName': "",
              'hotelMsg.phone': "",
              'hotelMsg.location': "",
              antiSnore_status: '关闭'
            })
            util.myHideLoading()
            if (app.globalData.bluetoothInfo != null) {

              await bluetoothUtils.closeBLEConnection(app.globalData.bluetoothInfo.deviceID)
              app.globalData.bluetoothInfo = null
            }
            if (app.globalData.bluetoothInfo2 != null) {
              await bluetoothUtils.closeBLEConnection(app.globalData.bluetoothInfo2.deviceID)
              app.globalData.bluetoothInfo2 = null
            }
          } else {
            console.log('error', res.data.msg)
            util.myShowToast(res.data.msg)
          }
        })
      }
      if (this.data.msg.btntext == "确定") {
        this.dataSwitch()
      }
      if (this.data.msg.btntext == "重新连接") {
        this.scan()
      }
    }
  },
  //注销账号&退出登录
  cancellation: function () {
    api.cancellation(app.globalData.token).then(res => {
      if (res.data.code == 200) {
        console.log('注销成功')
        app.globalData.token = null
        app.globalData.deviceId = null
        app.globalData.failDevice = null
        app.globalData.nopermission = true
        this.setData({
          hasConnect: false,
          hasUserData: false,
          'hotelMsg.hotelName': "",
          'hotelMsg.phone': "",
          'hotelMsg.location': ""
        })
        wx.clearStorageSync()
        if (app.globalData.bluetoothInfo != null) {
          bluetoothUtils.closeBLEConnection(app.globalData.bluetoothInfo.deviceID)
        }
        wx.switchTab({
          url: '/pages/index/index?nopermission=true',
        })
      } else {
        bluetoothUtils.myShowToast('服务器有点小问题')
        console.log('error', res.data.msg)
      }
    })
  },
  //蓝牙权限检查
  permissionCheck: function () {
    let _this = this
    wx.getSetting({
      withSubscriptions: true,
      success(res) {
        console.log('blue', res)
        // if (res.authSetting["scope.bluetooth"] == true && res.authSetting["scope.userLocation"] == true) {  蓝牙权限及位置权限是否打开(位置暂时不需要)
        if (res.authSetting["scope.bluetooth"] == true) {
          wx.openBluetoothAdapter({
            success: function (res) {
              if (app.globalData.deviceId != null) {
                wx.navigateTo({
                  url: '/pages/index/index',
                })
              } else {
                _this.scan()
              }
            },
            fail: function (res) { //手机上的蓝牙没有打开
              console.log('1111')
              _this.setData({
                bluetoothFlag: true
              })
            }
          })
        } else if (res.authSetting["scope.bluetooth"] == undefined) {
          util.myHideLoading()
          wx.authorize({
            scope: "scope.bluetooth",
            success() {
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
              _this.permissionCheck()
            }
          })
        } else if (res.authSetting["scope.bluetooth"] == false) {
          util.myHideLoading()
          _this.setData({
            bluetoothFlag2: true
          })
        }
      }
    })
  },
  //扫码
  scan: function () {
    let _this = this
    wx.scanCode({
      onlyFromCamera: true,
      success: async function (res) {
        console.log('扫码携带的参数', res)
        let bed_qrcode = ''
        let params = {}
        if (res.result) {
          if (res.result.length > 16) {
            bed_qrcode = res.result.split('#')[0].substring(res.result.split('#')[0].length - 16, res.result.split('#')[0].length)
          } else {
            bed_qrcode = res.result
          }
        } else if (res.q) {
          bed_qrcode = res.q.substring(res.q.length - 16, res.q.length)
        } else {}
        params.qrcode = bed_qrcode
        api.bedSide(params).then(res => {
          //获取床边信息完成
          if (res.data.code == 200) {
            if (res.data.data.left_device_id != null && res.data.data.right_device_id) {
              wx.navigateTo({
                url: '/pages/connect/bedside/bedside?obj=' + JSON.stringify(res.data.data),
              })
            } else {
              console.log(res)
              // util.myShowToast('请扫描正确二维码')
              _this.setData({
                dialogShow1: true,
                'msg.content': '连接失败，请重新扫码连接',
                'msg.btntext': '重新连接',
                'msg.title': '',
                'msg.tips': 3
              })
              return
            }
          } else {

          }
        })
      },
      fail: function (res) {
        util.myShowToast("用户操作已取消")
      }
    })
  },
  //展示提示
  showTips() {
    this.setData({
      tipsFlag: true
    })
  },
  //关闭提示
  closeTips() {
    this.setData({
      tipsFlag: false
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getUserInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        currentTab: 3
      })
    }
    this.getUserInfo()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})